﻿var viewModel = new function () {
	this.SearchKeyWord = ko.observable("");

	//Sort params
	this.ColName = ko.observable("");
	this.SortOrder = ko.observable("desc");

	// Filter params
	this.Lead = ko.observable();
	this.LeadOptions = ko.observableArray(data.ListLeadSource);
	this.Range = ko.observable(data.ListRange[7].RangeValue);
	this.RangeOptions = ko.observableArray(data.ListRange);
	this.RangeOption = ko.observable("true");
	this.FromDateEnable = ko.computed(function () {
		if (this.RangeOption() == "true")
			return true;

		return;
	}, this);
	this.RangeEnable = ko.computed(function () {
		if (this.RangeOption() == "false")
			return true;
		return;
	}, this);
	this.ToDateEnable = ko.computed(function () {
		if (this.RangeOption() == "true")
			return true;

		return;
	}, this);

	this.ReportItems = ko.observableArray(
		(!data.LeadInfo || !data.LeadInfo.LeadReportInfo) ? [] : data.LeadInfo.LeadReportInfo);
	// No results found!
	this.NoResultsFound = ko.computed(function() {
		return (!this.ReportItems() || !this.ReportItems().length);
	}, this);

	this.checkFirstLoadPage = ko.observable(0);

	// Pagination / Showing
	this.PageSize = ko.observable(10);
	this.CurrentPageIndex = ko.observable(1);
	this.MaxPageIndex = ko.observable(data.LeadInfo.TotalPages);

	// Next/Previous
	this.PrevPage = function () {
		var page = parseInt(this.CurrentPageIndex());
		if (page > 1) {
			this.CurrentPageIndex(page - 1);
			LoadDataFromServer();
		}
	}
	this.PrevButtonClass = ko.computed(function () {
		var page = parseInt(this.CurrentPageIndex());
		if (page > 1) {
			return "btn btn-prev-arrow prev-active";
		}
		else {
			return "btn btn-prev-arrow";
		}
	}, this);

	this.NextPage = function () {
		var page = parseInt(this.CurrentPageIndex());
		if (page < this.MaxPageIndex()) {
			this.CurrentPageIndex(page + 1);
			LoadDataFromServer();
		}
	}

	this.NextButtonClass = ko.computed(function () {
		if (this.CurrentPageIndex() == this.MaxPageIndex() || this.MaxPageIndex() == 1)
			return "btn btn-next-arrow next-disabled";
		else
			return "btn btn-next-arrow";
	}, this);


	///////////////////// Paging /////////////////////////////
	this.PageSizeText = ko.computed(function () {
		var pagevalue = this.PageSize().toString().replace(/\s/g, '');
		var PageSize = parseInt(pagevalue, 10);
		if (!IsNumeric(pagevalue))
			return "* Please enter a number between 1 - 100";
		else if (PageSize.toString() == 'NaN' || PageSize < 1 || PageSize > 100) {
			return "* Please enter a number between 1 - 100";
		}
		else {
			return "";
		}

	}, this);
	this.PageCurrentText = ko.computed(function () {
		var pagevalue = this.CurrentPageIndex().toString().replace(/\s/g, '');
		var pageindex = parseInt(pagevalue, 10);
		if (!IsNumeric(this.CurrentPageIndex()) || pagevalue == "")
			return "* Please enter a number between 1 - " + this.MaxPageIndex() + " ";
		else if (pagevalue.toString() == 'NaN' || !IsNumeric(pagevalue) || pageindex < 1 || pageindex > this.MaxPageIndex()) {
			return "* Please enter a number between 1 - " + this.MaxPageIndex() + " ";
		}

	}, this);

	this.search = function () {
		viewModel.CurrentPageIndex(1);
		LoadDataFromServer();
		RemoveSortIcons();
	}

	function SwitchSortOrder() {
		if (this.SortOrder === "asc") {
			this.SortOrder = "desc";
		} else {
			this.SortOrder = "asc";
		}
		return this.SortOrder;
	}

	function SetTHClass(event, colName) {
		RemoveSortIcons();

		if (viewModel.SortOrder() === "asc") {
			$("#" + colName).children("span").addClass("asc");
		} else {
			$("#" + colName).children("span").addClass("desc");
		}
	}
	function SetOrder(event, ColName) {
		if (this.dataReturnLeadReportList() != null) {
			if (this.dataReturnLeadReportList().length > 0) {
				if (this.ColName() === ColName) {
					this.SortOrder(SwitchSortOrder());
				} else {
					this.ColName(ColName);
					this.SortOrder("desc");
				}
				SetTHClass(event, ColName);
				LoadDataFromServer();
			}
		}
	}

	this.SetOrder = SetOrder; // Set to an knockout object

	// Load data
	function LoadDataFromServer() {

		var strPageSize = $("#pageshow").val();
		var strpageIndex = $("#pageIndex").val();
		if (strPageSize == "0") {
			strPageSize = "10";
		}
		if (strpageIndex == "0") {
			strpageIndex = "1";
		}

		// Page Size
		var pageSizeValue = $('#pageshow').val().toString().replace(/\s/g, '');
		var pagesize = parseInt(pageSizeValue, 10);
		if (!IsNumeric(pageSizeValue) || pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
			return false;
		}

		// Page Index
		var pageIndexValue = $('#pageIndex').val().toString().replace(/\s/g, '');
		var pageindex = parseInt(pageIndexValue, 10);
		if (viewModel.MaxPageIndex() > 0 && (!IsNumeric(pageIndexValue) || pageindex.toString() == 'NaN' || pageindex < 1 || pageindex > viewModel.MaxPageIndex())) {
			return false;
		}

		if (viewModel.RangeOption().toString() == "false") {
			var dataPost = { "leadSourceId": $("#selectLead").editableSelect('value'),
				"range": viewModel.Range(),
				"startDate": $('#startDate').val(),
				"endDate": $('#endDate').val(),
				"PageSize": strPageSize,
				"pageindex": strpageIndex,
				"sortorder": viewModel.SortOrder() + "ending"
			};
		}
		else {
			var dataPost = { "leadSourceId": $("#selectLead").editableSelect('value'),
				"range": "", "startDate": $('#startDate').val(),
				"endDate": $('#endDate').val(), "PageSize": strPageSize,
				"pageindex": strpageIndex,
				"sortorder": viewModel.SortOrder() + "ending"
			};
		}

		if (viewModel.CurrentPageIndex() <= viewModel.MaxPageIndex() || viewModel.MaxPageIndex() == 0) {
			// Progress bar
			openProcess();

			var urlPost = "/Reporting/SearchReturnLeads";
			$.ajax({
				type: "POST",
				url: urlPost,
				data: dataPost,
				dataType: "json",
				success: function (model, textStatus, jqXHR) {
					hideProcess();

					if (model && typeof model.LeadReportInfo != "undefined" && (typeof model.Error == "undefined" || !model.Error)) {
						viewModel.ReportItems(model.LeadReportInfo);
						viewModel.CurrentPageIndex(model.PageIndex);
						viewModel.MaxPageIndex(model.TotalPages);
					}
					else {
						viewModel.ReportItems([]);
						showPopupError();
					}
				},
				error: function (xhr, status, error) {
					hideProcess();

					viewModel.ReportItems([]);
					showPopupError();
				}
			}); // End ajax post
		}
		return false;
	}
	// PageSize/ PageCurrent keypress enter
	this.RunSomethingKey = function (viewModel, event) {
		if (event.keyCode == 13 || event.keyCode == 9) {
			viewModel.PageSize($('#pageshow').val());
			viewModel.CurrentPageIndex(1);
			LoadDataFromServer();
		}
		return true;
	}

	this.RunSomethingKey2 = function (viewModel, event) {
		if (event.keyCode == 13 || event.keyCode == 9) {
			viewModel.CurrentPageIndex($('#pageIndex').val());
			LoadDataFromServer();
		}
		return true;
	}

	function RemoveSortIcons() {
		$("div.title").parent().find(".sort_wrapper").children("span").removeClass("asc");
		$("div.title").parent().find(".sort_wrapper").children("span").removeClass("desc");
	}

	function SetResultString(strResult) {
		viewModel.SearchKeyWord(strResult);
	};

	// Call object refresh data
	this.RefreshDataByPageSize = function () {
		LoadDataFromServer();
	};
	this.RefreshDataByPageIndex = function () {
		LoadDataFromServer();
	};
};
ko.applyBindings(viewModel, document.getElementById("returnleadsreport"));
// Set CurrentDatetime for it
$('#startDate').blur(function () {
	setTimeout(function () {
		if (!isDateUS($('#startDate').val())) {
			$('#startDate').val(getCurrentDate());
		}
	}, 1);
});

$('#endDate').blur(function () {
	setTimeout(function () {
		if (!isDateUS($('#endDate').val())) {
			$('#endDate').val(getCurrentDate());
		}
	}, 1);
});

// Check datetime
function isDateTime(a) {
	var a = new Date(a);
	return ($.isNumeric(a.getTime()));
}

function hideProcess() {
	$('#popup-process').hide();
	$('.fancybox-skin').hide();
	$('#fancybox-overlay').hide();
}

$(document).ready(function () {
	$('#pageIndex').removeClass("text-active");

	// Live
	// Handle tab keypress event on input
//	$('#pageshow').live('keydown', function (e) {
//		var keyCode = e.keyCode || e.which;

//		if (keyCode == 9) {
//			e.preventDefault();
//			// call custom function here
//			viewModel.RefreshDataByPageSize();
//		}
//	});
//	$('#pageIndex').live('keydown', function (e) {
//		var keyCode = e.keyCode || e.which;

//		if (keyCode == 9) {
//			e.preventDefault();
//			// call custom function here
//			viewModel.RefreshDataByPageIndex();
//		}
//	});

	$('#selectLead').focus(function () {
		$(this).css("outline", "none");
	});
});

$(function () {
	$("#startDate").datepicker();
	$("#endDate").datepicker();
});

